﻿module app.service.base;


mixin template ServiceUtility(string table_name, T)
{
	import app.model.db;
	import std.experimental.logger;
	
	const string getTableName()
	{
		return this.tableName;
	}
	
	public{
		string tableName =table_name;
		static T _model;
	}
	
	static @property getInstance(){
		if(_model is null)
		{
			_model = new T();
		}
		return _model;
	}
	
	long getDataNumByWhere(string[string] whereCondition)
	{
		import std.array, std.conv;
		Appender!string sql = appender!string();
		sql.put("SELECT COUNT(*) AS total_count ");
		sql.put(" FROM \"");
		sql.put(getTableName());
		sql.put("\" ");
		
		string[] wheres;
		
		foreach(i, col; whereCondition) 
		{
			wheres ~= "\"" ~i~ "\"=" ~ DB().escapeLiteral(col);
		}
		if(wheres.length != 0 )
		{
			sql.put(" WHERE ");
			sql.put(wheres.join(" AND "));
		}
		
		trace("sql:", sql.data);
		auto result = DB().exec(sql.data);
		if(result.rows()==0)
		{
			return 0;
		}
		
		auto row = result.front;
		return to!long(row["total_count"].as!string().get());
	}
	
	
	bool updateByWhere(string[string] data, string[string] whereCondition)
	{
		import std.array, std.conv;
		Appender!string sql = appender!string();
		sql.put("UPDATE ");
		sql.put(getTableName());
		assert(data.length !=0, "update is null");
		string[] sets;
		foreach(i, col; data) 
		{
			sets ~= "\"" ~i~ "\"=" ~ DB().escapeLiteral(col);
		}
		if(sets.length != 0 )
		{
			sql.put(" SET ");
			sql.put(sets.join(" , "));
		}
		string[] wheres;
		
		foreach(i, col; whereCondition) 
		{
			wheres ~= "\"" ~i~ "\"=" ~ DB().escapeLiteral(col);
		}
		if(wheres.length != 0 )
		{
			sql.put(" WHERE ");
			sql.put(wheres.join(" AND "));
		}
		
		trace("sql:", sql.data);
		auto result = DB().exec(sql.data);
		if(result.rows()==0)
		{
			return false;
		}
		return true;
	}
	
	
	
	
	long getDataNumByWhere(string whereCondition)
	{
		import std.array, std.conv;
		Appender!string sql = appender!string();
		sql.put("SELECT COUNT(*) AS total_count ");
		sql.put(" FROM \"");
		sql.put(getTableName());
		sql.put("\" ");
		
		
		if(whereCondition.length != 0 )
		{
			sql.put(" WHERE ");
			sql.put(whereCondition);
		}
		
		trace("sql:", sql.data);
		auto result = DB().exec(sql.data);
		if(result.rows == 0)
		{
			return 0;
		}
		
		auto row = result.front;
		return to!long(row["total_count"].as!string().get());
	}
}
